package com.h2m.service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import com.servicelive.service.MailSenderService;
import com.servicelivedb.ServiceliveDB;
import com.servicelivedb.data.Order;
import com.servicelivedb.data.OrderItems;
import com.servicelivedb.data.output.GetTodaysVendorOrdersRtnType;
import com.wavemaker.runtime.RuntimeAccess;
import com.wavemaker.runtime.javaservice.JavaServiceSuperClass;
import com.wavemaker.runtime.service.annotations.ExposeToClient;

/**
 * This is a client-facing service class. All public methods will be exposed to
 * the client. Their return values and parameters will be passed to the client
 * or taken from the client, respectively. This will be a singleton instance,
 * shared between all requests.
 * 
 * To log, call the superclass method log(LOG_LEVEL, String) or log(LOG_LEVEL,
 * String, Exception). LOG_LEVEL is one of FATAL, ERROR, WARN, INFO and DEBUG to
 * modify your log level. For info on these levels, look for tomcat/log4j
 * documentation
 */
@ExposeToClient
public class OrderManageService extends JavaServiceSuperClass {
	/*
	 * Pass in one of FATAL, ERROR, WARN, INFO and DEBUG to modify your log
	 * level; recommend changing this to FATAL or ERROR before deploying. For
	 * info on these levels, look for tomcat/log4j documentation
	 */
	public OrderManageService() {
		super(INFO);
	}

	private String user;
	private String password;
	private String sid;
	private String url;

	public List<Order>getVendorOrderDetails(
			Integer vendorId, String projectName) {

		ServiceliveDB db = (ServiceliveDB) RuntimeAccess.getInstance()
				.getServiceBean("serviceliveDB");
		MailSenderService mailsend = (MailSenderService) RuntimeAccess
				.getInstance().getServiceBean("MailSenderService");
		List<GetTodaysVendorOrdersRtnType> vendorOrders = new ArrayList<GetTodaysVendorOrdersRtnType>();
		 VendorOrders orderDt = new VendorOrders();
		 List<Order> orders =null;
		try {
			System.out.println("vendorId====" + vendorId);

			db.begin();

			Session session = db.getDataServiceManager().getSession();
			// and ord.project.projectName= :projectName
			Query query = session
					.createQuery(" from Order ord where ord.orderDt >= current_date() and  ( ord.status = :statusNew OR  ord.status = :statusPartly ) and  ord.customerByVendorId.customerId =:vendorId  ORDER BY ord.orderDt desc");
			query.setInteger("vendorId", vendorId);
			// query.setString("projectName", projectName);
			query.setString("statusNew", "NEW");
			query.setString("statusPartly", "Partly Delivered");
			orders = query.list();
			System.out
					.println("$$$$$$$$$$$$$$$$$$$$$$$  Order $$$$$$$$$$$$$$$$$$$$$$$$");

			for (Order order : orders) {
				
				GetTodaysVendorOrdersRtnType dt = new GetTodaysVendorOrdersRtnType();
				vendorOrders.add(dt);

				dt.setComment(order.getComments() == null ? "" : order
						.getComments());
				dt.setContactNum("91" + order.getContactNum());
				dt.setCustomerId(order.getCustomerByCustomerId()
						.getCustomerId());
				dt.setCustomerName(order.getCustomerByCustomerId().getName());
				dt.setVendorId(order.getCustomerByVendorId().getCustomerId());
				dt.setOrderId(order.getOrderId());
				dt.setAddress(order.getAddress());
				dt.setOrderDt(order.getOrderDt());
				dt.setStatus(order.getStatus());
				dt.setPrice(order.getTotalPrice());
				StringBuilder items = new StringBuilder();
				for (OrderItems item : order.getOrderItemses()) {

					items.append(item.getQuantity().intValue()
							+ (item.getItems().getUnit() == null ? "" : item
									.getItems().getUnit()) + " "
							+ item.getItems().getItemName() + " "
							+ item.getItems().getPrice() + " "
							+ item.getItems().getCurrency());
					items.append("<br>");

				}
				dt.setDoorName(items.toString());

			}

			db.commit();

			 orderDt.setVendorOrders(vendorOrders);

			System.out.println("order is confirmed ::sending out email");


		} catch (Exception e) {
			db.rollback();
			System.out.println(e.getMessage());
			
			log(ERROR, "Error during updating order status", e);
		}
		return orders;
	}

	public String SMSSender(String msisdn, String msg) {
		String rsp = "";
		//String user = "TPSH2M";
		//String password = "829484";
		//String sid = "TPSHMI";
		String fl = "0";
		String retval = "";

		try {
			// Construct The Post Data
			String data = URLEncoder.encode("user", "UTF-8") + "="
					+ URLEncoder.encode(this.user, "UTF-8");
			data += "&" + URLEncoder.encode("password", "UTF-8") + "="
					+ URLEncoder.encode(this.password, "UTF-8");
			data += "&" + URLEncoder.encode("msisdn", "UTF-8") + "="
					+ URLEncoder.encode(msisdn, "UTF-8");
			data += "&" + URLEncoder.encode("msg", "UTF-8") + "="
					+ URLEncoder.encode(msg, "UTF-8");
			data += "&" + URLEncoder.encode("sid", "UTF-8") + "="
					+ URLEncoder.encode(this.sid, "UTF-8");
			data += "&" + URLEncoder.encode("fl", "UTF-8") + "="
					+ URLEncoder.encode(fl, "UTF-8");
			data += "&" + URLEncoder.encode("gwid", "UTF-8") + "="
					+ URLEncoder.encode("2", "UTF-8");

			// Push the HTTP Request
			URL url = new URL(this.url);
			URLConnection conn = url.openConnection();
			conn.setDoOutput(true);

			OutputStreamWriter wr = new OutputStreamWriter(
					conn.getOutputStream());
			wr.write(data);
			wr.flush();

			// Read The Response
			BufferedReader rd = new BufferedReader(new InputStreamReader(
					conn.getInputStream()));
			String line;
			while ((line = rd.readLine()) != null) {
				// Process line...
				retval += line;
			}
			wr.close();
			rd.close();

			System.out.println(retval);
			rsp = retval;

		} catch (Exception e) {
			e.printStackTrace();
		}
		return rsp;
	}

	public String ConstructTemplate(String vendorName, String customerName,
			String address, String phoneNumber, String orderId, String blockId,
			String doorId, String orderDetail) {
		String SmsTemplate = "Name : #Name# , Order No: #Order# Address : #Address# ,Block #block# ,Door #door# , Ph: #phone# , Item Details : #items# . Thanks, H2M.";
		String sMessage = "";
		sMessage = SmsTemplate.replaceFirst("#Name#", customerName);
		sMessage = sMessage.replaceFirst("#Order#", orderId);
		if (address != null && address != "") {
			sMessage = sMessage.replaceFirst("#Address#", address);
		} else {
			sMessage = sMessage.replaceFirst("#Address#", "No Address");
		}
		sMessage = sMessage.replaceFirst("#block#", blockId);
		sMessage = sMessage.replaceFirst("#door#", doorId);
		sMessage = sMessage.replaceFirst("#phone#", phoneNumber);
		sMessage = sMessage.replaceFirst("#items#", orderDetail);

		System.out.println("sMessage @@@" + sMessage);
		return sMessage;
	}

	public static class VendorOrders {

		private Integer customerId;
		private String comment;
		private List<GetTodaysVendorOrdersRtnType> vendorOrders;
		private Integer vendorId;

		public Integer getCustomerId() {
			return customerId;
		}

		public void setCustomerId(Integer customerId) {
			this.customerId = customerId;
		}

		public String getComment() {
			return comment;
		}

		public void setComment(String comment) {
			this.comment = comment;
		}

		public Integer getVendorId() {
			return vendorId;
		}

		public void setVendorId(Integer vendorId) {
			this.vendorId = vendorId;
		}

		public List<GetTodaysVendorOrdersRtnType> getVendorOrders() {
			return vendorOrders;
		}

		public void setVendorOrders(List<GetTodaysVendorOrdersRtnType> vendorOrders) {
			this.vendorOrders = vendorOrders;
		}

	}

	public String getUser() {
		return user;
	}

	public void setUser(String user) {
		this.user = user;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getSid() {
		return sid;
	}

	public void setSid(String sid) {
		this.sid = sid;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}
}
